import { resetRouter, asyncRouterList } from '@/router';
import router from '@/router';
import { MenuRoute } from '@/interface';
import Layout from '@/layouts/index.vue';

// 组件映射表，用于替代动态import
const componentMap = {
  // 基础页面
  '/dashboard/base': () => import('@/pages/dashboard/base/index.vue'),
  '/dashboard/detail': () => import('@/pages/dashboard/detail/index.vue'),
  
  // 设备管理相关页面
  // '/device': () => import('@/pages/device/index.vue'), // 设备父级路由
  '/device/list': () => import('@/pages/device/list/index.vue'),
  
  // 菜单管理
  '/menu': () => import('@/pages/menu/index.vue'),
  '/menu/authority': () => import('@/pages/menu/authority/index.vue'),
  '/menu/operationLog': () => import('@/pages/menu/operationLog/index.vue'),
  '/menu/account': () => import('@/pages/menu/account/index.vue'),
  '/menu/accRoles': () => import('@/pages/menu/accRoles/index.vue'),


  
  // 反馈页面
  '/feedback': () => import('@/pages/feedback/index.vue'),
  
  // 404页面
  '404': () => import('@/pages/result/404/index.vue')
};

// 获取组件
function getComponent(path) {
  if (!path) return null;
  // 处理路径格式一致性
  const normalizedPath = path.startsWith('/') ? path : `/${path}`;
  return componentMap[normalizedPath] || componentMap['404'];
}

// 简化的菜单构建函数，只处理两级菜单
function buildMenuTree(data) {
  const routes = [];
  
  if (!data || !Array.isArray(data)) {
    return routes;
  }

  // 第一层遍历：构建一级菜单
  data.forEach(item => {
    // 处理路径 - 一级路由需要以斜杠开头
    const routePath = item.component || '';
    const normalizedPath = routePath.startsWith('/') ? routePath : `/${routePath}`;
    
    // 创建路由对象
    const route: any = {
      path: normalizedPath, // 一级路由使用带斜杠的绝对路径
      name: item.name,
      component: Layout, // 一级菜单固定使用Layout组件
      meta: {
        title: item.name,
        icon: item.icon || '',
        closeable: item.meta?.closeable || true,
        roleCode: item.name,
      },
      children: []
    };
    
    // 处理子菜单：二级菜单
    if (item.children && item.children.length > 0) {
      item.children.forEach(child => {
        // 跳过没有component的子项
        if (!child.component) return;
        
        // 处理子菜单路径 - 子路由不需要以斜杠开头
        const childPath = child.component || '';
        const normalizedChildPath = childPath.startsWith('/') ? childPath.substring(1) : childPath;
        
        // 提取路径的最后一部分作为子路由路径
        // 例如：'/device/list' 应该变成 'list' 作为子路由的path
        const pathSegments = normalizedChildPath.split('/');
        const childRoutePath = pathSegments[pathSegments.length - 1];
        
        // 创建子路由
        const childRoute: any = {
          path: childRoutePath, // 子路由使用不带斜杠的相对路径
          name: child.name,
          component: getComponent(child.component),
          meta: {
            title: child.name,
            icon: child.icon || '',
            closeable: child.meta?.closeable || true,
            roleCode: child.name,
          }
        };
        
        route.children.push(childRoute);
      });
    }
    
    // 如果一级菜单没有子菜单但有组件，添加一个子路由重定向到自身
    if (route.children.length === 0 && item.component) {
      route.children.push({
        path: '', // 空路径，会匹配父路由
        component: getComponent(item.component),
        meta: { ...route.meta }
      });
    }
    
    // 只有存在有效子菜单或自身有组件的路由才添加
    if (route.children.length > 0) {
      routes.push(route);
    }
  });
  
  return routes;
}

// 将后端返回的菜单转换为路由配置
function transformMenuToRoutes(menuData) {
  if (!menuData || !Array.isArray(menuData)) {
    return [];
  }
  
  // 构建路由表
  const routes = buildMenuTree(menuData);
  console.log('转换后的路由:', routes);
  // 返回构建的路由
  return routes;
}

// 过滤权限路由
function filterPermissionsRouters(routes, roles) {
  const res = [];
  routes.forEach((route) => {
    const children = [];
    route.children?.forEach((childRouter) => {
      const roleCode = childRouter.meta?.roleCode || childRouter.name;
      if (roles.indexOf(roleCode) !== -1) {
        children.push(childRouter);
      }
    });
    if (children.length > 0) {
      route.children = children;
      res.push(route);
    }
  });
  return res;
}

const state = {
  whiteListRouters: ['/login'],
  routers: [],
  dynamicRoutes: [], // 存储从后端获取的动态路由
};

const mutations = {
  setRouters: (state, routers) => {
    state.routers = routers;
  },
  setDynamicRoutes: (state, routes) => {
    state.dynamicRoutes = routes;
  },
};

const getters = {
  routers: (state) => state.dynamicRoutes.length > 0 ? state.dynamicRoutes : state.routers,
  whiteListRouters: (state) => state.whiteListRouters,
};

const actions = {
  // 根据角色初始化路由
  async initRoutes({ commit }, roles) {
    let accessedRouters;

    // special token
    if (roles.includes('ALL_ROUTERS') || roles.includes('管理员')) {
      accessedRouters = asyncRouterList;
    } else {
      accessedRouters = filterPermissionsRouters(asyncRouterList, roles);
    }

    commit('setRouters', accessedRouters);
  },
  
  // 从后端获取到的菜单数据初始化动态路由
  async initDynamicRoutes({ commit }, menuData) {
    try {
      // 清除之前的动态路由
      resetRouter();
      
      // 将菜单数据转换为路由配置
      const dynamicRoutes = transformMenuToRoutes(menuData);
      
      // 注册动态路由
      dynamicRoutes.forEach(route => {
        try {
          if (!router.getRoutes().find(r => r.name === route.name)) {
            router.addRoute(route);
            console.log(`添加顶级路由: ${route.path} 成功`);
          }
        } catch (e) {
          console.error(`添加路由失败: ${route.path}`, e);
        }
      });
      
      commit('setDynamicRoutes', dynamicRoutes);
      console.log('动态路由初始化成功:', dynamicRoutes);
      
      return dynamicRoutes;
    } catch (error) {
      console.error('初始化动态路由失败:', error);
      return [];
    }
  },
  
  async restore({ commit }) {
    // remove routers
    resetRouter();
    commit('setRouters', []);
    commit('setDynamicRoutes', []);
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
